import {  PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import {  Tooltip,Button, Divider, message, Modal, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { Link,useModel } from 'umi';

import QRCode  from 'qrcode.react';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import DetailModel from './components/DetailModel';
import { queryPatrolJob, updatePatrolJob, addPatrolJob, removePatrolJob } from '@/services/patroljob';
import { queryDepartTree } from '@/services/department';


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addPatrolJob(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updatePatrolJob(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

//删除单个
const handleRemove = async (fields: any) => {
  const hide = message.loading('正在删除');
  try {
    await removePatrolJob({ id: fields.id });
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

const { confirm } = Modal;

const TableList: React.FC<{}> = () => {

  const [departmentTreeData, setDepartmentTreeData] = useState<API.TreeNodeItem[]>([]);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const { initialState } = useModel('@@initialState');
  const {currentUser} = initialState || {};

  const columns: ProColumns[] = [
    {
      title: '任务名称',
      dataIndex: 'jobName',
      render: (_,record) => 
      <Link to={'patrolJobDetails/' + record.id} > {_}</Link>
    }, 
   
    {
      title: '描述',
      dataIndex: 'memo',
    },
    {
      title: '责任部门',
      dataIndex: 'deptName',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      hideInSearch: true,
      valueEnum: {
        "": { text: '未提交', status: 'Wanning' },
        1: { text: '启用', status: 'Success' },
        0: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
          >
            编辑
          </a>
          {/* <Divider type="vertical" />
          <a onClick={async () => {
            handleDetailModalVisible(true);
            setFormValues(record);
          }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <Link to={'patrolJobDetails/' + record.id} >巡检项目</Link> */}
          <Divider type="vertical" />
          <Tooltip placement="top"   color={'white'} title={<div style={{padding:'12px'}}>  <a download id={'aId'+record.id} title="点我下载！"><QRCode
              value={`http://${currentUser.serverUrl}/mochaITOM/patrolRecordDetails1/${record.id}`}  //value参数为生成二维码的链接
              size={200} //二维码的宽高尺寸  
            
              id={'qrid'+record.id} 
              onClick={()=>clickDownLoad(record.id)}
              fgColor="#000000"  //二维码的颜色
          /></a></div>}>
            <Link to={"/mochaITOM/patrolRecordDetails1/"+record.id}  target="_blank">巡检</Link>
          </Tooltip >
           
        
          <Divider type="vertical" />
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await handleRemove(record);
                actionRef.current?.reload();
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  const setStateData = async () => {
    let trees = await queryDepartTree();
    setDepartmentTreeData(trees);
  };

  useEffect(() => {
    setStateData();
  }, []);

  //下载二维码
  const clickDownLoad=(id)=>{
    var Qr=document.getElementById('qrid'+id);  
    let image = new Image();
    image.src = Qr.toDataURL("image/png");
    var a_link=document.getElementById('aId'+id);
    a_link.href=image.src;
  }
  return (
    <>
      <ProTable
        headerTitle=""
        rowKey="id"
        actionRef={actionRef}
        tableAlertRender={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        toolbar={{
          settings: []
        }}
        search={{
          labelWidth: 'auto',
        }}
        rowSelection={{}}
        request={(params) => queryPatrolJob({ ...params })}
        columns={columns}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            setFormValues({});
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        treeData={departmentTreeData}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          treeData={departmentTreeData}
          values={formValues}
        />
      ) : null}
      {formValues && Object.keys(formValues).length ? (
        <DetailModel
          onCancel={() => {
            handleDetailModalVisible(false);
            setFormValues({});
          }}
          modalVisible={detailModalVisible}
          values={formValues}
        />
      ) : null}
    </>
  );
};

export default TableList;
